"""游戏管理器"""

import json
import uuid
from typing import Dict, List, Any, Optional
from models.character import Character, CharacterType
from models.skill import SkillLibrary
from .battle_engine import BattleEngine


class GameManager:
    """游戏管理器类"""
    
    def __init__(self):
        self.battle_engine = BattleEngine()
        self.battle_history: List[Dict[str, Any]] = []
    
    def create_sample_characters(self) -> tuple[List[Character], List[Character]]:
        """创建示例角色"""
        # 玩家方角色
        player_chars = [
            Character(
                id=f"player_{uuid.uuid4().hex[:8]}",
                name="战士",
                character_type=CharacterType.PLAYER,
                max_hp=120,
                current_hp=120,
                attack=25,
                defense=15,
                speed=12,
                hit_rate=85,
                dodge_rate=10,
                crit_rate=15,
                crit_damage=150
            ),
            Character(
                id=f"player_{uuid.uuid4().hex[:8]}",
                name="法师",
                character_type=CharacterType.PLAYER,
                max_hp=80,
                current_hp=80,
                attack=30,
                defense=8,
                speed=18,
                hit_rate=90,
                dodge_rate=15,
                crit_rate=20,
                crit_damage=180
            ),
            Character(
                id=f"player_{uuid.uuid4().hex[:8]}",
                name="治疗师",
                character_type=CharacterType.PLAYER,
                max_hp=90,
                current_hp=90,
                attack=15,
                defense=12,
                speed=16,
                hit_rate=80,
                dodge_rate=20,
                crit_rate=10,
                crit_damage=130
            )
        ]
        
        # 敌方角色
        enemy_chars = [
            Character(
                id=f"enemy_{uuid.uuid4().hex[:8]}",
                name="哥布林战士",
                character_type=CharacterType.ENEMY,
                max_hp=100,
                current_hp=100,
                attack=20,
                defense=10,
                speed=14,
                hit_rate=80,
                dodge_rate=12,
                crit_rate=12,
                crit_damage=140
            ),
            Character(
                id=f"enemy_{uuid.uuid4().hex[:8]}",
                name="哥布林法师",
                character_type=CharacterType.ENEMY,
                max_hp=70,
                current_hp=70,
                attack=28,
                defense=6,
                speed=20,
                hit_rate=85,
                dodge_rate=18,
                crit_rate=18,
                crit_damage=160
            )
        ]
        
        return player_chars, enemy_chars
    
    def setup_sample_battle(self) -> str:
        """设置示例战斗"""
        # 生成战斗ID
        battle_id = f"battle_{uuid.uuid4().hex[:8]}"
        
        # 创建战斗
        battle = self.battle_engine.create_battle(battle_id)
        
        # 创建角色
        player_chars, enemy_chars = self.create_sample_characters()
        
        # 设置角色位置
        # 我方角色放置在下方区域 (y = 3, 4, 5)
        player_setup = [
            {"character": player_chars[0], "x": 1, "y": 3},  # 战士在前排
            {"character": player_chars[1], "x": 0, "y": 4},  # 法师在后排
            {"character": player_chars[2], "x": 2, "y": 4}   # 治疗师在后排
        ]
        
        # 敌方角色放置在上方区域 (y = 0, 1, 2)
        enemy_setup = [
            {"character": enemy_chars[0], "x": 1, "y": 2},  # 哥布林战士在前排
            {"character": enemy_chars[1], "x": 2, "y": 1}   # 哥布林法师在后排
        ]
        
        # 设置角色
        if not self.battle_engine.setup_characters(player_setup, enemy_setup):
            raise Exception("角色设置失败")
        
        # 开始战斗
        if not self.battle_engine.start_battle():
            raise Exception("战斗开始失败")
        
        return battle_id
    
    def run_auto_battle(self, battle_id: Optional[str] = None) -> Dict[str, Any]:
        """运行自动战斗"""
        if battle_id is None:
            battle_id = self.setup_sample_battle()
        
        battle_log = {
            "battle_id": battle_id,
            "rounds": [],
            "final_result": None
        }
        
        max_rounds = 20  # 防止无限循环
        round_count = 0
        
        while round_count < max_rounds:
            round_count += 1
            
            # 执行一个回合
            round_result = self.battle_engine.auto_battle_round()
            
            if not round_result["success"]:
                battle_log["error"] = round_result["error"]
                break
            
            battle_log["rounds"].append({
                "round_number": round_result["round_number"],
                "actions": round_result["actions"]
            })
            
            # 检查战斗是否结束
            if round_result["battle_ended"]:
                battle_log["final_result"] = round_result["battle_result"]
                break
        
        # 如果达到最大回合数但战斗未结束，强制结束战斗
        if round_count >= max_rounds and battle_log["final_result"] is None:
            # 判断获胜方（根据剩余生命值）
            battle_state = self.battle_engine.get_battle_state()
            if battle_state:
                player_total_hp = sum(int(char['hp'].split('/')[0]) for char in battle_state['player_characters'] if char['is_alive'])
                enemy_total_hp = sum(int(char['hp'].split('/')[0]) for char in battle_state['enemy_characters'] if char['is_alive'])
                
                winner = CharacterType.PLAYER if int(player_total_hp) > int(enemy_total_hp) else CharacterType.ENEMY
                battle_log["final_result"] = self.battle_engine.current_battle.end_battle(winner).to_dict()
                battle_log["timeout"] = True
        
        # 保存到历史记录
        self.battle_history.append(battle_log)
        
        return battle_log
    
    def run_manual_battle_demo(self) -> Dict[str, Any]:
        """运行手动战斗演示"""
        battle_id = self.setup_sample_battle()
        
        battle_log = {
            "battle_id": battle_id,
            "actions": [],
            "final_result": None
        }
        
        # 演示几个手动操作
        demo_actions = [
            {"character_id": "player_1", "skill_id": "basic_attack", "target_x": 3, "target_y": 1},
            {"character_id": "enemy_1", "skill_id": "basic_attack", "target_x": 0, "target_y": 1},
            {"character_id": "player_2", "skill_id": "fireball", "target_x": 3, "target_y": 1},
            {"character_id": "enemy_2", "skill_id": "fireball", "target_x": 0, "target_y": 1},
            {"character_id": "player_3", "skill_id": "heal", "target_x": 0, "target_y": 1}
        ]
        
        for action in demo_actions:
            result = self.battle_engine.execute_turn(
                action["character_id"],
                action["skill_id"],
                action["target_x"],
                action["target_y"]
            )
            
            if result["success"]:
                battle_log["actions"].append(result["action"])
                
                if result["battle_ended"]:
                    battle_log["final_result"] = result["battle_result"]
                    break
            else:
                battle_log["error"] = result["error"]
                break
        
        return battle_log
    
    def get_battle_state(self) -> Optional[Dict[str, Any]]:
        """获取当前战斗状态"""
        return self.battle_engine.get_battle_state()
    
    def get_available_skills(self) -> Dict[str, Dict[str, Any]]:
        """获取可用技能"""
        return self.battle_engine.get_available_skills()
    
    def get_battle_history(self) -> List[Dict[str, Any]]:
        """获取战斗历史"""
        return self.battle_history
    
    def export_battle_result_json(self, battle_result: Dict[str, Any]) -> str:
        """导出战斗结果为JSON字符串"""
        return json.dumps(battle_result, ensure_ascii=False, indent=2)
    
    def create_custom_battle(self, player_data: List[Dict], enemy_data: List[Dict]) -> str:
        """创建自定义战斗
        
        Args:
            player_data: 玩家方数据 [{"name": str, "hp": int, "attack": int, "defense": int, "speed": int, "x": int, "y": int}, ...]
            enemy_data: 敌方数据，格式同上
        """
        battle_id = f"custom_battle_{uuid.uuid4().hex[:8]}"
        
        # 创建战斗
        battle = self.battle_engine.create_battle(battle_id)
        
        # 创建玩家方角色
        player_chars = []
        player_setup = []
        for i, data in enumerate(player_data):
            char = Character(
                id=f"player_{uuid.uuid4().hex[:8]}",
                name=data["name"],
                character_type=CharacterType.PLAYER,
                max_hp=data["hp"],
                current_hp=data["hp"],
                attack=data["attack"],
                defense=data["defense"],
                speed=data["speed"],
                hit_rate=data.get("hit_rate", 85),
                dodge_rate=data.get("dodge_rate", 15),
                crit_rate=data.get("crit_rate", 15),
                crit_damage=data.get("crit_damage", 150)
            )
            player_chars.append(char)
            player_setup.append({
                "character": char,
                "x": data["x"],
                "y": data["y"]
            })
        
        # 创建敌方角色
        enemy_chars = []
        enemy_setup = []
        for i, data in enumerate(enemy_data):
            char = Character(
                id=f"enemy_{uuid.uuid4().hex[:8]}",
                name=data["name"],
                character_type=CharacterType.ENEMY,
                max_hp=data["hp"],
                current_hp=data["hp"],
                attack=data["attack"],
                defense=data["defense"],
                speed=data["speed"],
                hit_rate=data.get("hit_rate", 80),
                dodge_rate=data.get("dodge_rate", 12),
                crit_rate=data.get("crit_rate", 12),
                crit_damage=data.get("crit_damage", 140)
            )
            enemy_chars.append(char)
            enemy_setup.append({
                "character": char,
                "x": data["x"],
                "y": data["y"]
            })
        
        # 设置角色
        if not self.battle_engine.setup_characters(player_setup, enemy_setup):
            raise Exception("角色设置失败")
        
        # 开始战斗
        if not self.battle_engine.start_battle():
            raise Exception("战斗开始失败")
        
        return battle_id